import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useAppDispatch, useAppSelector } from '@/store';
import { clearResultsAction, getResultsAction } from '@/store/action/search';
import { InfiniteScroll, Toast } from 'antd-mobile';
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult() {
  const location = useLocation();
  const dispatch = useAppDispatch();
  const { resultMap } = useAppSelector((state) => state.search);
  const urlParams = new URLSearchParams(location.search);
  const q = urlParams.get('q');

  useEffect(() => {
    if (!q) {
      Toast.show({ content: '查询关键字不能为空' });
      return;
    }

    dispatch(getResultsAction(q));

    return () => {
      dispatch(clearResultsAction());
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch]);

  const loadMore = async () => {
    await dispatch(getResultsAction(q as string, resultMap.page + 1));
  };
  return (
    <div className={styles.root}>
      <NavBar fixed>搜索结果</NavBar>
      <div className="article-list">
        {resultMap.results?.map((item) => (
          <ArticleItem key={item.art_id} data={item} />
        ))}
      </div>
      {resultMap.results?.length && (
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={resultMap.results?.length < resultMap.total_count}
        />
      )}
    </div>
  );
}
